package org.sky.cloud.common.filter;

import org.sky.cloud.api.exception.SkyException;
import org.sky.cloud.common.filter.request.IFilterRequest;
import org.sky.cloud.common.filter.response.IFilterResponse;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.ServiceLoader;

public class FilterChainManager implements IFilterChain{


    private final List<IFilter> filters = new ArrayList<>();

    public FilterChainManager(Properties properties){
        ServiceLoader<IFilter> filters = ServiceLoader.load(IFilter.class);
        for (IFilter filter : filters) {
            filter.init(properties);
            this.filters.add(filter);
        }
    }

    @Override
    public void doFilter(IFilterRequest request, IFilterResponse response) throws SkyException {
        new ExecFilterChain(filters).doFilter(request, response);
    }


    private static class ExecFilterChain implements IFilterChain{

        private List<IFilter> filters;

        private int currentIndex = 0;


        public ExecFilterChain(List<IFilter> filters) {
            this.filters = filters;
        }

        @Override
        public void doFilter(IFilterRequest request, IFilterResponse response) throws SkyException {
            if(currentIndex != filters.size()  ){
                currentIndex++;
                filters.get(currentIndex - 1).doFilter(request, response, this);
            }
        }
    }
}
